const sharp = require('sharp');
const fse = require('fs-extra');
const fs = require('fs');
const path = require('path');
const colors = require('colors-console')
const ffmpeg = require('fluent-ffmpeg');


// 显示帮助信息的函数
function showHelp() {
	console.log(colors('cyan', 'image-small@1.2.0'))
	console.log(colors('cyan', '------------------------------------------'))
	console.log(colors('green', 'Usage: image-small [imageFolder] [width]'));
	console.log(colors('green', 'Usage: image-small [videoFile] --video'));
	
	console.log(colors('red', 'This script is used to compress image or video files.'));
	console.log(colors('yellow', 'Supported image formats:.jpg,.jpeg,.png,.gif,.webp'));
	console.log(colors('yellow', 'Supported video formats:.mp4,.mov,.avi'));
	
	console.log(colors('cyan', '------------------------------------------'));
	process.exit(0);
}




// 辅助函数：将字节转换为更易读的格式
function formatBytes(bytes, decimals = 2) {
	if (bytes === 0) return '0 Bytes';
	const k = 1024;
	const dm = decimals < 0 ? 0 : decimals;
	const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
	const i = Math.floor(Math.log(bytes) / Math.log(k));
	return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

async function compressImagesInFolder(folderPath, width) {
	try {
		const files = await fse.readdir(folderPath);
		for (const file of files) {
			const fileExtension = path.extname(file).toLowerCase();
			const supportedExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
			if (supportedExtensions.includes(fileExtension)) {
				const filePath = path.join(folderPath, file);
				const outputPath = path.join(folderPath, 'compressed_' + file);

				// 获取原始文件大小
				const {
					size: originalSize
				} = await fse.stat(filePath);
				await sharp(filePath).resize({
					width
				}).toFile(outputPath);
				// 获取压缩后文件大小
				const {
					size: compressedSize
				} = await fse.stat(outputPath);
				const osize = formatBytes(originalSize, 2);
				const csize = formatBytes(compressedSize, 2);
				let compressionRate;
				if (originalSize === 0) {
					compressionRate = 0;
				} else {
					compressionRate = (100 - (parseInt(compressedSize / originalSize * 100)));
				}
				console.log(colors('cyan', `${file}: 压缩前${osize}，压缩后${csize}，压缩率${compressionRate}%`));

				// 如果需要删除原始文件并将压缩后的文件重命名为原始文件名，可以取消下面两行注释
				await fse.remove(filePath);
				await fse.rename(outputPath, filePath);
			}
		}
		console.log(colors('cyan', 'Images in the folder have been compressed successfully.'));
	} catch (error) {
		console.error('Error compressing images', error);
	}
}


const supportedFormats = ['.mp4', '.avi', '.mkv'];
async function compressVideosInFolder(filePath, options = {
	width: 854,
	height: 480
}) {

	// 获取输入文件的绝对路径和目录
	const inputPath = path.resolve(filePath);
	const inputDir = path.dirname(inputPath);
	// 构建输出文件的名称
	const outputFileName = 'compressed_' + path.basename(inputPath, path.extname(inputPath)) + '.mp4';
	const outputPath = path.join(inputDir, outputFileName);

	const startTime = Date.now(); // 记录开始时间


	// 执行ffmpeg操作
	const process = ffmpeg(inputPath)
		.outputOptions('-s 854x480')
		.videoCodec('libx264')
		.audioCodec('copy')
		.format('mp4')
		.on('end', function() {
			const endTime = Date.now(); // 记录结束时间
			const duration = (endTime - startTime) / 1000; // 计算处理时长，单位为秒
			console.log(colors('green', `视频处理完成，处理时间:  ${duration} 秒`));
		})
		.on('error', function(err) {
			console.log('视频处理出错:', err);
		})
		.on('progress', function(progress) {
			// 计算处理进度百分比并显示
			let percent = progress.percent || 0;
			console.log(colors('yellowBG', `处理进度: ${percent.toFixed(2)}%`));
		})
		// .option('workers', 4);
	process.save(outputPath);


}


module.exports = {
	compressImagesInFolder,
	showHelp,
	compressVideosInFolder
}